<?php
/**
 * receive.php
 *
 * Author: Lomo
 * Date: 2018-06
 * Email: lomo@lomo.space
 * URL: http://lomo.space
 *
 * Description:
 * 第二种 消息消费方式: basic_consume
 * 先运行：php receiver.php, 启动消费者，然后在运行生产者，没运行一次生产者产生消息后，消费者就会读取到一条.
 *
 */

    require_once __DIR__ . '/vendor/autoload.php';
    use PhpAmqpLib\Connection\AMQPStreamConnection;


    $connection = new AMQPStreamConnection('localhost', 5672, 'guest', 'guest');
    $channel = $connection->channel();

    //$channel->queue_declare('lomo1', false, false, false, false);
    //
    //echo ' [*] Waiting for messages. To exit press CTRL+C', "\n";
    //
    //$callback = function($msg) {
    //    echo " [x] Received ", $msg->body, "\n";
    //};
    //$channel->basic_consume('lomo1', '', false, true, false, false, $callback);
    //while(count($channel->callbacks)) {
    //    $channel->wait();
    //}
    //
    //$channel->close();
    //$connection->close();

    // 消息队列名 和 生产者队列名一致
    $channel->queue_declare('lomo1', false, false, false, false);
    echo '等待获取 lomo1 队列中的消息...', "\n";

    $callback = function ($msg) {
        echo 'Received message: ', $msg->body, "\r\n";
    };

    // 接收到消息后 执行回调callback函数(打印消息)
    $channel->basic_consume('lomo1', '', false, true, false, false, $callback);

    while (count($channel->callbacks)) {
        $channel->wait();
    }

    $channel->close();
    $connection->close();

